package com.wstuo.common.Luence;
import java.io.File;
import java.io.IOException;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import com.wstuo.common.security.utils.AppConfigUtils;
import com.wstuo.common.util.StringUtils;

import java.nio.file.Path;
import java.util.Map;
/**
 * 作用:lucene 全文搜索
 * @author Qiu
 *
 */
public class LuenceUtil {
	private static LuenceUtil instance=null;
	private static Directory directory =null;
	private	static Analyzer analyzer=null;
	
	private LuenceUtil(){
		if(analyzer==null){
			analyzer = new StandardAnalyzer();
		}
		
	}
	public static LuenceUtil getInstance(String module) {
		if(instance==null){
			instance = new LuenceUtil();
		}
		// 存储索引在内存中:
	    //Directory directory = new RAMDirectory();
		File file=new File(AppConfigUtils.getInstance().getIndexPath()+File.separator+module);
		if (!file.exists()) {
			file.mkdirs();
		}
		
		Path p=file.toPath();
	    try {
			directory = FSDirectory.open(p);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return instance;
	}
	public void add(Map<String, String> map){
		IndexWriterConfig config = new IndexWriterConfig(analyzer);
	    try {
			IndexWriter iwriter = new IndexWriter(directory, config);
			iwriter.addDocument(addDocument(map));
			iwriter.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	private Document addDocument(Map<String, String> map){
		Document doc=new Document();
		for (Map.Entry<String, String> entry : map.entrySet()) {
			doc.add(new Field(entry.getKey(), entry.getValue(), TextField.TYPE_STORED));
		}
		return doc;
	}
  	/**
     * Description： 更新索引
     * @param id
     * @param title
     * @param content
     */
    public void update(Map<String, String> map){
        try {
            IndexWriterConfig config = new IndexWriterConfig(analyzer);
            IndexWriter indexWriter = new IndexWriter(directory,config);
            Term term = new Term("id",map.get("id"));
            indexWriter.updateDocument(term, addDocument(map));
            indexWriter.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 
     * Description：按照ID删除索引
     * @param id
     */
    public void delete(Long id){
        try {
            IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer);
            IndexWriter indexWriter = new IndexWriter(directory,indexWriterConfig);
            Term term = new Term("id",String.valueOf(id));
            indexWriter.deleteDocuments(term);
            indexWriter.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
	public Long[] search(String str,String[] multiFields){
		if(!StringUtils.hasText(str)) return null;
		DirectoryReader ireader;
		Long[] ids=null;
		try {
			ireader = DirectoryReader.open(directory);
			IndexSearcher isearcher = new IndexSearcher(ireader);
			//String[] multiFields = { "fieldname", "content" };
		    MultiFieldQueryParser parser = new MultiFieldQueryParser( multiFields, analyzer);
		      
		    // 设定具体的搜索词
		    Query query = parser.parse(str);
		    TopDocs docs =isearcher.search(query,null, 10);//查找
		    ScoreDoc[] hits = docs.scoreDocs;
		    
		    System.out.println("共查找到 " + hits.length + " 条内容.");
	        if(hits.length>0){
	        	ids=new Long[hits.length];
	        }
	        for (int i = 0; i < hits.length; i++) {
	            Document hitDoc = isearcher.doc(hits[i].doc);
	            ids[i]=Long.parseLong(hitDoc.get("id"));
	        }
	        ireader.close();
	        directory.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 
	    return ids;
       
	}
   public static void test(){
//       SimpleHTMLFormatter simpleHTMLFormatter = new SimpleHTMLFormatter("<span style='color:red'>", "</span>");//把查找到的数据着色输出
//       Highlighter highlighter = new Highlighter(simpleHTMLFormatter, new QueryScorer(query));
//        //高亮htmlFormatter对象  
//       //设置高亮附近的字数  
//       highlighter.setTextFragmenter(new SimpleFragmenter(100));  
        
       // Iteratethrough the results:
  }
}
